当前位置:  开发笔记 > 编程语言 > 正文

你的PowerShell`profile.ps1`文件中有什么?

如何解决《你的PowerShell`profile.ps1`文件中有什么?》经验,为你挑选了11个好方法。

您的个人资料中包含哪些基本内容(功能,别名,启动脚本)?



1> Raoul Superc..:

我经常发现自己需要一些基本的agregates来计算/总结一些东西.我已经定义了这些函数并经常使用它们,它们在管道的末尾非常好地工作:

#
# useful agregate
#
function count
{
    BEGIN { $x = 0 }
    PROCESS { $x += 1 }
    END { $x }
}

function product
{
    BEGIN { $x = 1 }
    PROCESS { $x *= $_ }
    END { $x }
}

function sum
{
    BEGIN { $x = 0 }
    PROCESS { $x += $_ }
    END { $x }
}

function average
{
    BEGIN { $max = 0; $curr = 0 }
    PROCESS { $max += $_; $curr += 1 }
    END { $max / $curr }
}

为了能够在我的提示中获得颜色的时间和路径:

function Get-Time { return $(get-date | foreach { $_.ToLongTimeString() } ) }
function prompt
{
    # Write the time 
    write-host "[" -noNewLine
    write-host $(Get-Time) -foreground yellow -noNewLine
    write-host "] " -noNewLine
    # Write the path
    write-host $($(Get-Location).Path.replace($home,"~").replace("\","/")) -foreground green -noNewLine
    write-host $(if ($nestedpromptlevel -ge 1) { '>>' }) -noNewLine
    return "> "
}

以下功能是从博客中窃取并修改以符合我的口味,但颜色的ls非常好:

# LS.MSH 
# Colorized LS function replacement 
# /\/\o\/\/ 2006 
# http://mow001.blogspot.com 
function LL
{
    param ($dir = ".", $all = $false) 

    $origFg = $host.ui.rawui.foregroundColor 
    if ( $all ) { $toList = ls -force $dir }
    else { $toList = ls $dir }

    foreach ($Item in $toList)  
    { 
        Switch ($Item.Extension)  
        { 
            ".Exe" {$host.ui.rawui.foregroundColor = "Yellow"} 
            ".cmd" {$host.ui.rawui.foregroundColor = "Red"} 
            ".msh" {$host.ui.rawui.foregroundColor = "Red"} 
            ".vbs" {$host.ui.rawui.foregroundColor = "Red"} 
            Default {$host.ui.rawui.foregroundColor = $origFg} 
        } 
        if ($item.Mode.StartsWith("d")) {$host.ui.rawui.foregroundColor = "Green"}
        $item 
    }  
    $host.ui.rawui.foregroundColor = $origFg 
}

function lla
{
    param ( $dir=".")
    ll $dir $true
}

function la { ls -force }

还有一些快捷方式可以避免重复的过滤任务:

# behave like a grep command
# but work on objects, used
# to be still be allowed to use grep
filter match( $reg )
{
    if ($_.tostring() -match $reg)
        { $_ }
}

# behave like a grep -v command
# but work on objects
filter exclude( $reg )
{
    if (-not ($_.tostring() -match $reg))
        { $_ }
}

# behave like match but use only -like
filter like( $glob )
{
    if ($_.toString() -like $glob)
        { $_ }
}

filter unlike( $glob )
{
    if (-not ($_.tostring() -like $glob))
        { $_ }
}


这个评论没有任何价值,但我只是想说你的用户名很棒.

2> Scott Saad..:

要从PowerShell设置我的Visual Studio构建环境,我从这里获取了VsVars32 .并一直使用它.

###############################################################################
# Exposes the environment vars in a batch and sets them in this PS session
###############################################################################
function Get-Batchfile($file) 
{
    $theCmd = "`"$file`" & set" 
    cmd /c $theCmd | Foreach-Object {
        $thePath, $theValue = $_.split('=')
        Set-Item -path env:$thePath -value $theValue
    }
}


###############################################################################
# Sets the VS variables for this PS session to use
###############################################################################
function VsVars32($version = "9.0")
{
    $theKey = "HKLM:SOFTWARE\Microsoft\VisualStudio\" + $version
    $theVsKey = get-ItemProperty $theKey
    $theVsInstallPath = [System.IO.Path]::GetDirectoryName($theVsKey.InstallDir)
    $theVsToolsDir = [System.IO.Path]::GetDirectoryName($theVsInstallPath)
    $theVsToolsDir = [System.IO.Path]::Combine($theVsToolsDir, "Tools")
    $theBatchFile = [System.IO.Path]::Combine($theVsToolsDir, "vsvars32.bat")
    Get-Batchfile $theBatchFile
    [System.Console]::Title = "Visual Studio " + $version + " Windows Powershell"
}



3> halr9000..:

这将遍历脚本PSDrive并点源所有以"lib-"开头的内容.

### ---------------------------------------------------------------------------
### Load function / filter definition library
### ---------------------------------------------------------------------------

    Get-ChildItem scripts:\lib-*.ps1 | % { 
      . $_
      write-host "Loading library file:`t$($_.name)"
    }



4> jwmiller5..:

开始成绩单.这会将整个会话写入文本文件.非常适合培训新员工如何在环境中使用Powershell.


+1感谢您的提示...这只是修复了我的问题,将持续集成构建记录到控制台和日志文件.我很失望在"Windows Powershell袖珍参考"或"Windows PowerShell in Action"中都没有记录.我想这是你从练习中学到的东西.

5> Jay Bazuzi..:

我的提示包含:

$width = ($Host.UI.RawUI.WindowSize.Width - 2 - $(Get-Location).ToString().Length)
$hr = New-Object System.String @('-',$width)
Write-Host -ForegroundColor Red $(Get-Location) $hr

这给了我一个命令之间的分隔符,当滚动回来时很容易看到.它还向我显示当前目录,而不使用我正在键入的行上的水平空格.

例如:

C:\ Users\Jay -------------------------------------------- -------------------------------------------------- ------------
[1] PS>



6> JaredPar..:

这是我不那么微妙的个人资料

    #==============================================================================
# Jared Parsons PowerShell Profile (jaredp@rantpack.org) 
#==============================================================================

#==============================================================================
# Common Variables Start
#==============================================================================
$global:Jsh = new-object psobject 
$Jsh | add-member NoteProperty "ScriptPath" $(split-path -parent $MyInvocation.MyCommand.Definition) 
$Jsh | add-member NoteProperty "ConfigPath" $(split-path -parent $Jsh.ScriptPath)
$Jsh | add-member NoteProperty "UtilsRawPath" $(join-path $Jsh.ConfigPath "Utils")
$Jsh | add-member NoteProperty "UtilsPath" $(join-path $Jsh.UtilsRawPath $env:PROCESSOR_ARCHITECTURE)
$Jsh | add-member NoteProperty "GoMap" @{}
$Jsh | add-member NoteProperty "ScriptMap" @{}

#==============================================================================

#==============================================================================
# Functions 
#==============================================================================

# Load snapin's if they are available
function Jsh.Load-Snapin([string]$name) {
    $list = @( get-pssnapin | ? { $_.Name -eq $name })
    if ( $list.Length -gt 0 ) {
        return; 
    }

    $snapin = get-pssnapin -registered | ? { $_.Name -eq $name }
    if ( $snapin -ne $null ) {
        add-pssnapin $name
    }
}

# Update the configuration from the source code server
function Jsh.Update-WinConfig([bool]$force=$false) {

    # First see if we've updated in the last day 
    $target = join-path $env:temp "Jsh.Update.txt"
    $update = $false
    if ( test-path $target ) {
        $last = [datetime] (gc $target)
        if ( ([DateTime]::Now - $last).Days -gt 1) {
            $update = $true
        }
    } else {
        $update = $true;
    }

    if ( $update -or $force ) {
        write-host "Checking for winconfig updates"
        pushd $Jsh.ConfigPath
        $output = @(& svn update)
        if ( $output.Length -gt 1 ) {
            write-host "WinConfig updated.  Re-running configuration"
            cd $Jsh.ScriptPath
            & .\ConfigureAll.ps1
            . .\Profile.ps1
        }

        sc $target $([DateTime]::Now)
        popd
    }
}

function Jsh.Push-Path([string] $location) { 
    go $location $true 
}
function Jsh.Go-Path([string] $location, [bool]$push = $false) {
    if ( $location -eq "" ) {
        write-output $Jsh.GoMap
    } elseif ( $Jsh.GoMap.ContainsKey($location) ) {
        if ( $push ) {
            push-location $Jsh.GoMap[$location]
        } else {
            set-location $Jsh.GoMap[$location]
        }
    } elseif ( test-path $location ) {
        if ( $push ) {
            push-location $location
        } else {
            set-location $location
        }
    } else {
        write-output "$loctaion is not a valid go location"
        write-output "Current defined locations"
        write-output $Jsh.GoMap
    }
}

function Jsh.Run-Script([string] $name) {
    if ( $Jsh.ScriptMap.ContainsKey($name) ) {
        . $Jsh.ScriptMap[$name]
    } else {
        write-output "$name is not a valid script location"
        write-output $Jsh.ScriptMap
    }
}


# Set the prompt
function prompt() {
    if ( Test-Admin ) { 
        write-host -NoNewLine -f red "Admin "
    }
    write-host -NoNewLine -ForegroundColor Green $(get-location)
    foreach ( $entry in (get-location -stack)) {
        write-host -NoNewLine -ForegroundColor Red '+';
    }
    write-host -NoNewLine -ForegroundColor Green '>'
    ' '
}

#==============================================================================

#==============================================================================
# Alias 
#==============================================================================
set-alias gcid      Get-ChildItemDirectory
set-alias wget      Get-WebItem
set-alias ss        select-string
set-alias ssr       Select-StringRecurse 
set-alias go        Jsh.Go-Path
set-alias gop       Jsh.Push-Path
set-alias script    Jsh.Run-Script
set-alias ia        Invoke-Admin
set-alias ica       Invoke-CommandAdmin
set-alias isa       Invoke-ScriptAdmin
#==============================================================================

pushd $Jsh.ScriptPath

# Setup the go locations
$Jsh.GoMap["ps"]        = $Jsh.ScriptPath
$Jsh.GoMap["config"]    = $Jsh.ConfigPath
$Jsh.GoMap["~"]         = "~"

# Setup load locations
$Jsh.ScriptMap["profile"]       = join-path $Jsh.ScriptPath "Profile.ps1"
$Jsh.ScriptMap["common"]        = $(join-path $Jsh.ScriptPath "LibraryCommon.ps1")
$Jsh.ScriptMap["svn"]           = $(join-path $Jsh.ScriptPath "LibrarySubversion.ps1")
$Jsh.ScriptMap["subversion"]    = $(join-path $Jsh.ScriptPath "LibrarySubversion.ps1")
$Jsh.ScriptMap["favorites"]     = $(join-path $Jsh.ScriptPath "LibraryFavorites.ps1")
$Jsh.ScriptMap["registry"]      = $(join-path $Jsh.ScriptPath "LibraryRegistry.ps1")
$Jsh.ScriptMap["reg"]           = $(join-path $Jsh.ScriptPath "LibraryRegistry.ps1")
$Jsh.ScriptMap["token"]         = $(join-path $Jsh.ScriptPath "LibraryTokenize.ps1")
$Jsh.ScriptMap["unit"]          = $(join-path $Jsh.ScriptPath "LibraryUnitTest.ps1")
$Jsh.ScriptMap["tfs"]           = $(join-path $Jsh.ScriptPath "LibraryTfs.ps1")
$Jsh.ScriptMap["tab"]           = $(join-path $Jsh.ScriptPath "TabExpansion.ps1")

# Load the common functions
. script common
. script tab
$global:libCommonCertPath = (join-path $Jsh.ConfigPath "Data\Certs\jaredp_code.pfx")

# Load the snapin's we want
Jsh.Load-Snapin "pscx"
Jsh.Load-Snapin "JshCmdlet" 

# Setup the Console look and feel
$host.UI.RawUI.ForegroundColor = "Yellow"
if ( Test-Admin ) {
    $title = "Administrator Shell - {0}" -f $host.UI.RawUI.WindowTitle
    $host.UI.RawUI.WindowTitle = $title;
}

# Call the computer specific profile
$compProfile = join-path "Computers" ($env:ComputerName + "_Profile.ps1")
if ( -not (test-path $compProfile)) { ni $compProfile -type File | out-null }
write-host "Computer profile: $compProfile"
. ".\$compProfile"
$Jsh.ScriptMap["cprofile"] = resolve-path ($compProfile)

# If the computer name is the same as the domain then we are not 
# joined to active directory
if ($env:UserDomain -ne $env:ComputerName ) {
    # Call the domain specific profile data
    write-host "Domain $env:UserDomain"
    $domainProfile = join-path $env:UserDomain "Profile.ps1"
    if ( -not (test-path $domainProfile))  { ni $domainProfile -type File | out-null }
    . ".\$domainProfile"
}

# Run the get-fortune command if JshCmdlet was loaded
if ( get-command "get-fortune" -ea SilentlyContinue ) {
    get-fortune -timeout 1000
}

# Finished with the profile, go back to the original directory
popd

# Look for updates
Jsh.Update-WinConfig

# Because this profile is run in the same context, we need to remove any 
# variables manually that we don't want exposed outside this script



7> Christopher ..:

我摇滚一些功能,因为我是模块作者,我通常加载一个控制台,迫切需要知道它在哪里.

write-host "Your modules are..." -ForegroundColor Red
Get-module -li

死硬的神经:

function prompt
{
    $host.UI.RawUI.WindowTitle = "ShellPower"
    # Need to still show the working directory.
    #Write-Host "You landed in $PWD"

    # Nerd up, yo.
    $Str = "Root@The Matrix"
    "$str> "
}

强制性的任何我可以PowerShell我将功能去这里...

# Explorer command
function Explore
{
    param
        (
            [Parameter(
                Position = 0,
                ValueFromPipeline = $true,
                Mandatory = $true,
                HelpMessage = "This is the path to explore..."
            )]
            [ValidateNotNullOrEmpty()]
            [string]
            # First parameter is the path you're going to explore.
            $Target
        )
    $exploration = New-Object -ComObject shell.application
    $exploration.Explore($Target)
}

我仍然是管理员所以我确实需要......

Function RDP
{
    param
        (
            [Parameter(
                    Position = 0,
                    ValueFromPipeline = $true,
                    Mandatory = $true,
                    HelpMessage = "Server Friendly name"
            )]
            [ValidateNotNullOrEmpty()]
            [string]
            $server
        )

    cmdkey /generic:TERMSRV/$server /user:$UserName /pass:($Password.GetNetworkCredential().Password)
    mstsc /v:$Server /f /admin
    Wait-Event -Timeout 5
    cmdkey /Delete:TERMSRV/$server
}

有时我想启动资源管理器作为登录用户以外的人...

# Restarts explorer as the user in $UserName
function New-Explorer
{
    # CLI prompt for password

    taskkill /f /IM Explorer.exe
    runas /noprofile /netonly /user:$UserName explorer
}

这只是因为它很有趣.

Function Lock-RemoteWorkstation
{
    param(
        $Computername,
        $Credential
    )

    if(!(get-module taskscheduler))
    {
        Import-Module TaskScheduler
    }
    New-task -ComputerName $Computername -credential:$Credential |
        Add-TaskTrigger -In (New-TimeSpan -Seconds 30) |
        Add-TaskAction -Script `
        {
            $signature = @"
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool LockWorkStation();
            "@
                $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru
                $LockWorkStation::LockWorkStation() | Out-Null
        } | Register-ScheduledTask TestTask -ComputerName $Computername -credential:$Credential
}

我也有一个给我,因为Win+ L太远了......

Function llm # Lock Local machine
{
    $signature = @"
    [DllImport("user32.dll", SetLastError = true)]
    public static extern bool LockWorkStation();
    "@
        $LockWorkStation = Add-Type -memberDefinition $signature -name "Win32LockWorkStation" -namespace Win32Functions -passthru

        $LockWorkStation::LockWorkStation() | Out-Null
}

一些过滤器?我认同...

 filter FileSizeBelow($size){if($_.length -le $size){ $_ }}
 filter FileSizeAbove($size){if($_.Length -ge $size){$_}}

我还有一些我还不能发帖,因为它们没有完成,但它们基本上是一种在会话之间保留凭据而不将其作为加密文件写出来的方法.



8> user15071..:
# ----------------------------------------------------------
# msdn search for win32 APIs.
# ----------------------------------------------------------

function Search-MSDNWin32
{

    $url = 'http://search.msdn.microsoft.com/?query=';

    $url += $args[0];

    for ($i = 1; $i -lt $args.count; $i++) {
        $url += '+';
        $url += $args[$i];
    }

    $url += '&locale=en-us&refinement=86&ac=3';

    Open-IE($url);
}

# ----------------------------------------------------------
# Open Internet Explorer given the url.
# ----------------------------------------------------------

function Open-IE ($url)
{    
    $ie = new-object -comobject internetexplorer.application;

    $ie.Navigate($url);

    $ie.Visible = $true;
}


而不是`Open-IE`我使用`Invoke-Item`的内置`ii`别名.

9> Ed Guiness..:

中肯.

虽然我认为这已被最近或即将发布的版本所取代.

############################################################################## 
## Search the PowerShell help documentation for a given keyword or regular 
## expression.
## 
## Example:
##    Get-HelpMatch hashtable
##    Get-HelpMatch "(datetime|ticks)"
############################################################################## 
function apropos {

    param($searchWord = $(throw "Please specify content to search for"))

    $helpNames = $(get-help *)

    foreach($helpTopic in $helpNames)
    {
       $content = get-help -Full $helpTopic.Name | out-string
       if($content -match $searchWord)
       { 
          $helpTopic | select Name,Synopsis
       }
    }
}



10> tomasr..:

我保留了一切.大多数情况下,我的配置文件设置了所有环境(包括调用脚本来设置我的.NET/VS和Java开发环境).

我还prompt()使用自己的样式重新定义了该函数(请参阅其中的操作),为其他脚本和命令设置了几个别名.并改变$HOME指向的内容.

这是我完整的个人资料脚本.



11> 小智..:

我添加此功能,以便我可以轻松地看到磁盘使用情况:

function df {
    $colItems = Get-wmiObject -class "Win32_LogicalDisk" -namespace "root\CIMV2" `
    -computername localhost

    foreach ($objItem in $colItems) {
        write $objItem.DeviceID $objItem.Description $objItem.FileSystem `
            ($objItem.Size / 1GB).ToString("f3") ($objItem.FreeSpace / 1GB).ToString("f3")

    }
}

推荐阅读
周扒pi
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有